#!/usr/bin/env python

import os,sys

tests=[]
test=["","","","",""]
for line in open("spftest.txt"):
        if line[0]=="#":
                continue
        if len(line)==1:
                tests.append(test)
                test=["","","","",""]

        if line.startswith("spfquery "):
                pos1=line.find("-ip=")
                pos2=line.find(" ",pos1)
                test[0]=line[pos1+4:pos2]

                pos1=line.find("-sender=")
                pos2=line.find(" ",pos1)
                test[1]=line[pos1+8:pos2]

                pos1=line.find("-helo=")
                pos2=line.find(" ",pos1)
                test[2]=line[pos1+6:pos2]


        if line.startswith("result"):
                pos1=line.rfind(" ")
                test[4]=line[pos1+1:-1].lower()

err=0
ok=0
fail=0
counter=1
res=""

for test in tests:

        if test == ["","","","",""]:
                continue

        print "Test nr. ",counter

        command="./raspfquery"
        command+=' --ip "'+test[0]+'"'
        command+=' --sender "'+test[1]+'"'
        command+=' --helo "'+test[2]+'"'

        print command

        p=os.popen(command+" 2>&1","r")
        for line in p:
                if "response:" in line:
                        res=''.join(line.split(":")[1:]).strip()
                        l=line
        ex=p.close()
        if ex:  # Probably a segfault
                fail=fail+1
                print "FAIL"

        if test[4]==res:
                print "OK"
                ok+=1
        else:
                print "ERROR"
                print test
                print res
                fail+=1

        counter=counter+1


if fail+err > 0:
        print "TEST NOT SUCCESSFUL"
else:
        print "TEST SUCCESSFUL"
print
print "OK:   ",ok
print "ERR:  ",err
print "FAIL: ",fail
